package com.example.livedatademo;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Observer;

import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import java.util.Random;

public class MainActivity extends AppCompatActivity {

    //添加一个被MutableLiveData包装的变量
    private MutableLiveData<Integer> count = new MutableLiveData<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //添加监听
        addObserver();
        // 改变包装对象的值  进行监听的触发
        addClick();

    }

    private void addObserver() {
        count.observe(this, new Observer<Integer>() {
            @Override
            public void onChanged(Integer integer) {
                Toast.makeText(MainActivity.this, String.valueOf(integer), Toast.LENGTH_LONG).show();
            }
        });
    }

    private void addClick() {
        findViewById(R.id.layout).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //驱动数据变化
                count.setValue(new Random().nextInt());
            }
        });
    }
}